package pri.damai.xiaowu.common.core.handler;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import pri.damai.xiaowu.common.core.enums.ResultCommonEnum;
import pri.damai.xiaowu.common.core.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/6/9 15:07
 * 但行好事，莫问前程。
 */
@Slf4j
public class ValidExceptionHandler {

    /**
     * 处理 valid 参数验证异常信息
     * @apiNote [附加描述]
     * @param e 异常信息
     * @return com.ruiruan.pre.common.core.vo.ResultVO<java.lang.String>
     * @author DaMai
     * @date 2021/6/9 15:19
     */
    public ResultVO<String> handle(Exception e) {
        String msg = null;

        //参数无效异常
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException t = (MethodArgumentNotValidException) e;
            msg = getBindingResultMsg(t.getBindingResult());
        }

        //参数绑定校验异常
        if (e instanceof BindException) {
            BindException t = (BindException) e;
            msg = getBindingResultMsg(t.getBindingResult());
        }

        // 请求缺少Servlet参数异常
        if (e instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException t = (MissingServletRequestParameterException) e;
            msg = t.getParameterName() + " 不能为空";
        }

        if (e instanceof MissingPathVariableException) {
            MissingPathVariableException t = (MissingPathVariableException) e;
            msg = t.getVariableName() + " 不能为空";
        }

        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException t = (ConstraintViolationException) e;
            msg = t.getLocalizedMessage();
        }

        if (msg == null) {
            msg = "参数未知错误";
        }

        log.warn("参数校验未通过,msg: {}。", msg, e);

        //拼装统一返回
        return ResultVO.error(ResultCommonEnum.PARAM_ERROR.code(), msg);
    }

    /**
     * 拼接错误信息
     * @apiNote [描述此方法]
     * @param result
     * @return java.lang.String
     * @author DaMai
     * @date 2021/1/25 15:31
     */
    private String getBindingResultMsg(BindingResult result) {

        return result.getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
    }

}
